import {Button, Card, Divider, Form, Input, message, Row, Select, Space, Typography} from "antd";
import React, {useState} from "react";
import {baseURL} from "../../utils/request.js";
import ReactMarkdown from "react-markdown";
import SimpleExample from "./SimpleExample/index.jsx";

const {TextArea} = Input;
const {Paragraph} = Typography;

// 总时间选择配置
const totalTimeOptions = [
    {
        label: '15秒',
        value: '15'
    },
    {
        label: '30秒',
        value: '30'
    },
    {
        label: '45秒',
        value: '45'
    },
    {
        label: '60秒',
        value: '60'
    },
    {
        label: '75秒',
        value: '75'
    },
    {
        label: '90秒',
        value: '90'
    },
    {
        label: '105秒',
        value: '105'
    },
    {
        label: '120秒',
        value: '120'
    }
]

// 主题选择配置
const themeOptions = [
    {
        label: '有情',
        value: '有情'
    },
    {
        label: '有趣',
        value: '有趣'
    },
    {
        label: '有用',
        value: '有用'
    },
    {
        label: '有品',
        value: '有品'
    }
]


// 感情基调配置
const emotionOptions = [
    {
        label: '无',
        value: ''
    },
    {
        label: '欢快',
        value: '欢快'
    },
    {
        label: '忧愁',
        value: '忧愁'
    },
    {
        label: '寂寞',
        value: '寂寞'
    },
    {
        label: '伤感',
        value: '伤感'
    },
    {
        label: '恬淡',
        value: '恬淡'
    },
    {
        label: '闲适',
        value: '闲适'
    },
    {
        label: '思念',
        value: '思念'
    },
]

// 场景氛围配置
const sceneOptions = [
    {
        label: '无',
        value: ''
    },
    {
        label: '热烈',
        value: '热烈'
    },
    {
        label: '孤寂',
        value: '孤寂'
    },
    {
        label: '友好',
        value: '友好'
    },
    {
        label: '无助',
        value: '无助'
    }
]

// 剧情结构配置 转折、跌宕起伏、悬念、反转、升华、疑云
const structOptions = [
    {
        label: '无',
        value: ''
    },
    {
        label: '转折',
        value: "转折"
    },
    {
        label: '跌宕起伏',
        value: "跌宕起伏"
    },
    {
        label: '悬念',
        value: '悬念'
    },
    {
        label: '反转',
        value: '反转'
    },
    {
        label: '升华',
        value: '升华'
    },
    {
        label: '疑云',
        value: '疑云'
    }
]

const ShortVideoScript = () => {

    // 表头配置
    const columns = [
        {
            title: '时间段',
            dataIndex: 'timePeriod',
            key: 'timePeriod',
            render: (_, record, index) => (
                <Paragraph
                    editable={{
                        onChange: (newValue) => changeTimePeriod(newValue, index),
                    }}
                >
                    {record.timePeriod}
                </Paragraph>
            ),
        },
        {
            title: '场景描述',
            dataIndex: 'scenarioDescription',
            key: 'scenarioDescription',
            render: (_, record, index) => (
                <Paragraph
                    editable={{
                        onChange: (newValue) => changeScenarioDescriptiond(newValue, index),
                    }}
                >
                    {record.scenarioDescription}
                </Paragraph>
            ),
        },
        {
            title: '角色动作与台词',
            dataIndex: 'roleAction',
            key: 'roleAction',
            render: (_, record, index) => (
                <Paragraph
                    editable={{
                        onChange: (newValue) => changeRoleAction(newValue, index),
                    }}
                >
                    {record.roleAction}
                </Paragraph>
            ),
        },
        {
            title: '背景音乐与效果',
            key: 'bgm',
            dataIndex: 'bgm',
            render: (_, record, index) => (
                <Paragraph
                    editable={{
                        onChange: (newValue) => changeBgm(newValue, index),
                    }}
                >
                    {record.bgm}
                </Paragraph>
            ),
        },
        {
            title: '景别',
            key: 'scenery',
            dataIndex: 'scenery',
            render: (_, record, index) => (
                <Paragraph
                    editable={{
                        onChange: (newValue) => changeScenery(newValue, index),
                    }}
                >
                    {record.scenery}
                </Paragraph>
            ),
        },
    ];


    // 脚本数据
    const [scriptData, setScriptData] = useState([])

    // 编辑时间段
    const changeTimePeriod = (newValue, index) => {
        // console.log(newValue,index)
        let data = scriptData
        data[index].timePeriod = newValue
        // console.log(data)
        setScriptData([...data])
    }

    // 编辑场景描述
    const changeScenarioDescriptiond = (newValue, index) => {
        let data = scriptData
        data[index].scenarioDescription = newValue
        setScriptData([...data])
    }

    // 编辑角色动作与台词
    const changeRoleAction = (newValue, index) => {
        let data = scriptData
        data[index].roleAction = newValue
        setScriptData([...data])
    }

    // 编辑背景音乐
    const changeBgm = (newValue, index) => {
        let data = scriptData
        data[index].bgm = newValue
        setScriptData([...data])
    }

    // 编辑景别
    const changeScenery = (newValue, index) => {
        let data = scriptData
        data[index].scenery = newValue
        setScriptData([...data])
    }

    // 请求数据
    const [reqData, setReqData] = useState({
        totalTime: '15',
        theme: "",
        emotion: '',
        scene: "",
        struct: '',
        content: ''
    })

    // 修改总时间
    const changeTotalTime = (e) => {
        setReqData({
            ...reqData,
            totalTime: e
        })
    }

    // 修改主题
    const changeTheme = (e) => {
        setReqData({
            ...reqData,
            theme: e.target.value
        })
    }

    // 修改场景
    const changeScene = (e) => {
        setReqData({
            ...reqData,
            scene: e
        })
    }

    // 修改剧情结构
    const changeStruct = (e) => {
        setReqData({
            ...reqData,
            struct: e
        })
    }

    // 修改感情基调
    const changeEmotion = (e) => {
        // console.log(e)
        setReqData({
            ...reqData,
            emotion: e
        })
    }

    // 修改自定义的内容
    const changeContent = (e) => {
        setReqData({
            ...reqData,
            content: e.target.value
        })
    }

    // 确定生成
    const confirmDraw = async (example) => {
        console.log(reqData)
        setDrawStatus(true)


        if (example) {
            console.log('666')
            let data = {
                totalTime: '15',
                theme: "小学生放学回家",
                emotion: '欢快',
                scene: "热烈",
                struct: '转折',
                content: '五个小学生放学回家'
            }

            const resp = await fetch(baseURL + '/api/v1/chat/shot/video', {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8',
                    Authorization: window.localStorage.getItem('token'),
                    // Authorization: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvb2lZWTZXMW1TUUpLYXFXVGxzd2hkYXdHeXBnIiwib3BlbklkIjoib29pWVk2VzFtU1FKS2FxV1Rsc3doZGF3R3lwZyIsImV4cCI6MTcxNDQ2MDkzMiwidXNlcklkIjoiMzY3NDQ2NDI3NTI3Mjg2Nzg0IiwiaWF0IjoxNzEzODU2MTMyLCJqdGkiOiI3ZmE3YjllZS1jZjlhLTQ5YzQtOWEzMS1mMWQzNGU5M2I3ZmEifQ.5eFcsrK62ASy8ecogKBTek6TgEQsn8pOjUcue9sGI90'
                },
                body: JSON.stringify(
                    {
                        model: window.localStorage.getItem('gpt'),
                        messages: [data],
                        controller: "false"
                    }
                )
            })

            const reader = resp.body.getReader()

            let tempScriptData = ''
            const textDecoder = new TextDecoder()
            while (1) {
                const {done, value} = await reader.read()
                if (done) {
                    break
                }
                const str = textDecoder.decode(value)

                tempScriptData += str
                console.log('示例视频脚本', tempScriptData)
                setDrewScriptData(tempScriptData)
            }

            setDrawStatus(false)

            return
        }

        let localData = window.localStorage.getItem('scriptHistory')

        let arr = []
        if (localData) {
            arr = JSON.parse(localData)
            if (arr.length >= 4) {
                arr.shift()
            }
            arr.push(reqData)

        } else {
            arr.push(reqData)
        }

        const resp = await fetch(baseURL + '/api/v1/chat/shot/video', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                Authorization: window.localStorage.getItem('token'),
                // Authorization: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvb2lZWTZXMW1TUUpLYXFXVGxzd2hkYXdHeXBnIiwib3BlbklkIjoib29pWVk2VzFtU1FKS2FxV1Rsc3doZGF3R3lwZyIsImV4cCI6MTcxNDQ2MDkzMiwidXNlcklkIjoiMzY3NDQ2NDI3NTI3Mjg2Nzg0IiwiaWF0IjoxNzEzODU2MTMyLCJqdGkiOiI3ZmE3YjllZS1jZjlhLTQ5YzQtOWEzMS1mMWQzNGU5M2I3ZmEifQ.5eFcsrK62ASy8ecogKBTek6TgEQsn8pOjUcue9sGI90'
            },
            body: JSON.stringify(
                {
                    model: window.localStorage.getItem('gpt'),
                    messages: arr,
                    controller: "false"
                }
            )
        })

        const reader = resp.body.getReader()

        let tempScriptData = ''
        const textDecoder = new TextDecoder()
        while (1) {
            const {done, value} = await reader.read()
            if (done) {
                break
            }
            const str = textDecoder.decode(value)

            tempScriptData += str
            console.log('视频脚本', tempScriptData)
            setDrewScriptData(tempScriptData)
        }

        setDrawStatus(false)

        saveToLocal(reqData)
    }

    //     将数据保存本地
    const saveToLocal = (formData) => {

        let scriptHistory = window.localStorage.getItem('scriptHistory')
        if (scriptHistory) {
            let arr = JSON.parse(scriptHistory)
            if (arr.length === 5) {
                arr.shift()
            }
            arr.push(formData)

            console.log(arr)
            window.localStorage.setItem('scriptHistory', JSON.stringify(arr))
        } else {
            let arr = []
            arr.push(formData)
            console.log(arr)
            window.localStorage.setItem('scriptHistory', JSON.stringify(arr))
        }
    }

    // 生成状态
    const [drawStatus, setDrawStatus] = useState(false)

    // 复制脚本数据
    const copyText = () => {

        // let resultData = ''
        //
        // scriptData.forEach((item) => {
        //     let strItem = ''
        //     strItem += item.timePeriod + '  ' + item.scenarioDescription + '  ' + item.roleAction + '  ' + item.bgm + '  ' + item.scenery + '\n'
        //     resultData += strItem
        // })
        navigator.clipboard.writeText(drewScriptData)
            .then(() => {
                console.log('复制成功');
                message.success('复制成功👻')
            })
            .catch(err => {
                console.error('复制失败', err);
                message.error('复制失败🤷‍♂️',);
            })
    }


    // 生成txt文件保存本地
    const saveText = () => {
// 要保存的字符串
//         let resultData = ''
//
//         scriptData.forEach((item) => {
//             let strItem = ''
//             strItem += item.timePeriod + '  ' + item.scenarioDescription + '  ' + item.roleAction + '  ' + item.bgm + '  ' + item.scenery + '\n'
//             resultData += strItem
//         })
        // dada 表示要转换的字符串数据，type 表示要转换的数据格式
        const blob = new Blob([drewScriptData], {
            type: "text/plain;charset=utf-8"
        })
        // 根据 blob生成 url链接
        const objectURL = URL.createObjectURL(blob)

        // 创建一个 a 标签Tag
        const aTag = document.createElement('a')
        // 设置文件的下载地址
        aTag.href = objectURL
        // 设置保存后的文件名称
        aTag.download = 'FusionMind' + new Date().getFullYear().toString() + new Date().getMonth().toString() + new Date().getDay().toString() + new Date().getTime().toString() + ".txt"
        // 给 a 标签添加点击事件
        aTag.click()
        // 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
        // 当你结束使用某个 URL 对象之后，应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
        URL.revokeObjectURL(objectURL)
    }

    // 脚本数据
    const [drewScriptData, setDrewScriptData] = useState('')

    return (
        <>
            <Card style={{width: '100%'}}>
                <Row style={{marginTop: 0, width: '100%'}}>
                    <Form
                        layout={'inline'}
                        initialValues={{totalTime: '15', emotion: '', scene: '', struct: ''}}
                    >
                        <Form.Item
                            label="视频总时间"
                            name="totalTime"
                        >
                            <Select
                                style={{
                                    width: 120,
                                }}
                                options={totalTimeOptions}
                                onChange={changeTotalTime}
                            />
                        </Form.Item>

                        {/*<Form.Item*/}
                        {/*    label="主题"*/}
                        {/*    name="theme"*/}
                        {/*>*/}
                        {/*    <Select*/}
                        {/*        defaultValue=""*/}
                        {/*        style={{*/}
                        {/*            width: 120,*/}
                        {/*        }}*/}
                        {/*        options={themeOptions}*/}
                        {/*    />*/}
                        {/*</Form.Item>*/}


                        <Form.Item
                            label="剧情感情基调"
                            name="emotion"
                        >
                            <Select

                                style={{
                                    width: 120,
                                }}
                                onChange={changeEmotion}
                                options={emotionOptions}
                            />
                        </Form.Item>


                        <Form.Item
                            label="场景氛围"
                            name="scene"
                        >
                            <Select
                                style={{
                                    width: 120,
                                }}
                                options={sceneOptions}
                                onChange={changeScene}
                            />
                        </Form.Item>


                        <Form.Item
                            label="剧情结构"
                            name="struct"
                        >
                            <Select
                                style={{
                                    width: 120,
                                }}
                                options={structOptions}
                                onChange={(e) => changeStruct(e)}
                            />
                        </Form.Item>
                    </Form>
                </Row>


                <div className="myform">
                    <Form layout={'vertical'}>
                        <Form.Item label={'主题'} name='theme'>
                            <TextArea autoSize={{
                                minRows: 3,
                                maxRows: 6
                            }} placeholder="输入主题" value={reqData.theme} onChange={changeTheme} allowClear/>
                        </Form.Item>

                        <Form.Item label={'内容'}>
                            <TextArea autoSize={{
                                minRows: 3,
                                maxRows: 6
                            }} onChange={(e) => changeContent(e)} placeholder="自定义输入的内容"
                                      value={reqData.content}
                                      allowClear style={{width: '100%'}}/>
                        </Form.Item>


                        <Form.Item>
                            <Button type="primary" loading={drawStatus} onClick={confirmDraw}>确定生成</Button>
                        </Form.Item>
                    </Form>
                </div>


                {/*<Table style={{marginTop: 10}} rowKey={record => record.timePeriod} columns={columns}*/}
                {/*       dataSource={scriptData}*/}
                {/*       pagination={false}/>*/}

                {/*{drewScriptData && <Typography>*/}
                {/*    <Paragraph>*/}
                {/*        /!*<blockquote>{blockContent}</blockquote>*!/*/}
                {/*        <pre> {drewScriptData}</pre>*/}
                {/*    </Paragraph>*/}
                {/*</Typography>}*/}

                {drewScriptData &&
                    <ReactMarkdown>
                        {drewScriptData}
                    </ReactMarkdown>
                }

                {scriptData.length > 0 && <Row justify={'start'} style={{marginTop: 10}}>
                    <Space size={"middle"}>
                        <Button type={'primary'} onClick={copyText}>
                            复制
                        </Button>
                        <Button type={'primary'} onClick={saveText}>
                            下载
                        </Button>
                    </Space>
                </Row>}


                <Divider/>

                {!drewScriptData && <SimpleExample startDraw={confirmDraw}></SimpleExample>}
            </Card>
        </>
    )
}

export default ShortVideoScript
